package site.assad.web;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;
import site.assad.domain.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * Author: Al-assad 余林颖
 * E-mail: yulinying_1994@outlook.com
 * Date: 2018/1/2 13:43
 * Description:  Excel 视图实现 bean
 */
public class UserListExcelView extends AbstractExcelView {

    @Override
    protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //excel 文件编码必须为“iso8859-1“，否则会出现乱码
        response.setHeader("Content-Disposition","inline;filename=" + new String("用户列表".getBytes(),"iso8859-1"));
        List<User> userList = (List<User>) model.get("userList");
        //创建excel表格
        HSSFSheet sheet = workbook.createSheet("users");
        //创建行首
        HSSFRow header = sheet.createRow(0);
        header.createCell(0).setCellValue("账号");
        header.createCell(1).setCellValue("用户名");
        header.createCell(2).setCellValue("生日");
        //填充模型
        int rowNum = 1;
        for(User user : userList){
            HSSFRow row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(user.getUserId());
            row.createCell(1).setCellValue(user.getUserName());
            row.createCell(2).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday()));
        }
    }
}
